/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.gs.gms.messanger;


import static com.gs.gms.common.GmsCommonConstants.SERVER_BASE_ADDRESS;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 *
 * @author Sabuj
 */
public class BasicAuthenticationClient {
    private static final String LOGOUT_URL = SERVER_BASE_ADDRESS + "logout.htm";
    
    private final HttpClient httpClient;
    private final String host;
    private final int port;
    
	/**
	 * Constructor for BasicAuthenticationClient.
     * @param host
     * @param port
	 */
	public BasicAuthenticationClient(String host, int port) {
		httpClient = new HttpClient();
        this.host = host;
        this.port = port;
	}

    public HttpClient getHttpClient() {
        return httpClient;
    }
 
    /**
     *
     * @param userName
     * @param password
     * @return
     */
    public String login(String userName, String password) throws HttpException, IOException {
        List<String> authPrefs = new ArrayList<>(2);
		authPrefs.add(AuthPolicy.DIGEST);
		authPrefs.add(AuthPolicy.BASIC);
		httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
		httpClient.getParams().setAuthenticationPreemptive(true);
		httpClient.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM),
				new UsernamePasswordCredentials(userName, password));
        
        PostMethod postMethod = new PostMethod(SERVER_BASE_ADDRESS);
        postMethod.setDoAuthentication(true);
        try {
			// execute the POST
			int status = httpClient.executeMethod(postMethod);
            if(HttpStatus.SC_OK == status){
                Cookie[] cookies = httpClient.getState().getCookies();
                if(null != cookies && cookies.length > 0){
                    for (Cookie cookie : cookies) {
                        if(cookie.getName().equals("GMS_SESSION_ID")){
                            System.out.println("After login: GMS_SESSION_ID=" + cookie.getValue());
                            return cookie.getValue();
                        }
                    }
                }
            }
		}  finally {
			// release any connection resources used by the method
			postMethod.releaseConnection();
		}
        return null;
    }   
    
	private void logout() throws HttpException, IOException {
		// create a GET method that reads a file over HTTPS, we're assuming
		// that this file requires basic authentication using the realm above.
		GetMethod get = new GetMethod(LOGOUT_URL);
		try {
			// execute the GET
			int status = httpClient.executeMethod(get);

			// print the status and response
			System.out.println(status + httpClient.getState().toString() + "\n" + get.getStatusLine()
					+ get.getResponseBodyAsString());

		} finally {
			// release any connection resources used by the method
			get.releaseConnection();
		}
	}

    public static void main(String[] args) {
		
		BasicAuthenticationClient example = new BasicAuthenticationClient("localhost", 8080);

		try {
			System.out.println(example.login("admin", "admin"));
			//example.logout();
            
            
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			
                    
		}
	}
}
